export default function(Vue, config) {
    // 从参数中解构 baseUrl参数
    const { baseUrl, path } = config;
	// 添加全局方法
	Vue.prototype.http = async function(params) {
		// 请求参数
		let url = params.url || '',
			method = params.method || 'get',
			data = params.data || {};

		let requestData = data;
		let userinfo = this.$store.state.data;
		method = method.toUpperCase();
		// 真正的请求发出
		const [err, res] = await uni.request({
			url: baseUrl + path + url,
			method,
			data: requestData,
			header: {
				'Content-Type': 'application/x-www-form-urlencoded',
				'UID': userinfo.uid || '',
				'TOKEN': userinfo.token || '',
			},
		});
		let response = requestResultHandel(err, res, this);
		return response;
	};
	Vue.prototype.uploadApi = async function(params){

		const { url, filePath, name, formData } = params;
		const [err, res] = await uni.uploadFile({
			url: baseUrl + path + url,
			filePath,
			name,
			formData,
		});
		return requestResultHandel(err, res, this);
	};
	Vue.prototype.domainApi = baseUrl;

	let requestResultHandel = (err, res, _this) => {
		if (err !== null) {
			uni.showToast({title: '系统错误', icon: 'none'});
			return false;
		}
		let response = res.data;
		if (typeof response === 'string') response = JSON.parse(response);
		if (response.status === 40001 || response.status === 40002) {
			_this.$store.commit('logout');
			uni.navigateTo({url: '/pages/login/index'});
			return false;
		}
		if (response.status !== 0) {
			uni.showToast({title: response.msg || '系统错误', icon: 'none'});
			return false;
		}
		return response;
	};
}
